package com.zy.cat.service.impl;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Period;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import org.apache.commons.lang3.RandomUtils;
import org.apache.tomcat.util.codec.binary.Base64;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import com.zy.cat.common.config.Configs;
import com.zy.cat.common.utils.AesEncryptUtils;
import com.zy.cat.common.utils.DateAPIUtils;
import com.zy.cat.common.utils.DrawProportionUtil;
import com.zy.cat.common.utils.TJKUtils;
import com.zy.cat.dao.Dao;
import com.zy.cat.entity.app.resp.CatAppVersionInfoResp;
import com.zy.cat.entity.dev.CatDev5088InviteIncomeHistory;
import com.zy.cat.entity.dev.CatDevHCInviteIncomeHistory;
import com.zy.cat.entity.dev.CatDevHCRemitInfo;
import com.zy.cat.entity.dev.CatDevRelation;
import com.zy.cat.entity.dev.CatDevUserInfo;
import com.zy.cat.entity.dev.repository.CatDev5088InviteIncomeHistoryRepository;
import com.zy.cat.entity.dev.repository.CatDevHCInviteIncomeHistoryRepository;
import com.zy.cat.entity.dev.repository.CatDevHCRemitInfoRepository;
import com.zy.cat.entity.dev.repository.CatDevRelationRepository;
import com.zy.cat.entity.dev.repository.CatDevRemitInfoRepository;
import com.zy.cat.entity.dev.repository.CatDevUserInfoRepository;
import com.zy.cat.entity.dev.resp.CatDev5088InviteInfoResp;
import com.zy.cat.entity.dev.resp.CatDev5088InviteInfoResp.InviteHistory;
import com.zy.cat.entity.dev.resp.CatDev5088InviteInfoResp.InviteRemit;
import com.zy.cat.entity.dev.resp.CatDevHCInviteHistoryResp;
import com.zy.cat.entity.dev.resp.CatDevHCInviteInfoResp;
import com.zy.cat.entity.dev.resp.CatDevHCInviteInfoResp.IncomeData;
import com.zy.cat.entity.dev.resp.CatDevInviteTeamInfoResp;
import com.zy.cat.entity.dev.resp.CatDevInviteUrlInfoResp;
import com.zy.cat.entity.dev.resp.CatDevOrderResp;
import com.zy.cat.entity.dev.resp.CatDevRebateInfoResp;
import com.zy.cat.entity.dev.resp.CatDevRemitRecordResp;
import com.zy.cat.entity.dev.resp.CatDevTeamRebateResp;
import com.zy.cat.entity.dev.resp.CatDevUserInfoResp;
import com.zy.cat.entity.dev.resp.CatDevUserInfoResp.TLJInfo;
import com.zy.cat.entity.dev.resp.CatDevZJInviteDetailedResp;
import com.zy.cat.entity.dev.resp.CatDevZJInviteDetailedResp.InvitedPersonData;
import com.zy.cat.entity.dev.resp.CatDevZJInviteInfoResp;
import com.zy.cat.entity.resp.Pages;
import com.zy.cat.entity.resp.ResultPage;
import com.zy.cat.service.AsyncService;
import com.zy.cat.service.CacheService;
import com.zy.cat.service.CatDevInviteService;
import com.zy.cat.service.CatDevService;

import lombok.extern.slf4j.Slf4j;

/**
 * 
 * @info
 * @author Link
 * @date 2019-11-26 14:29
 */
@Service
@Slf4j
public class CatDevInviteServiceImpl implements CatDevInviteService {

	@Autowired
	CatDevRelationRepository catDevRelationRepository;

	@Autowired
	CatDevHCInviteIncomeHistoryRepository catDevHCInviteIncomeHistoryRepository;

	@Autowired
	CatDevUserInfoRepository catDevUserInfoRepository;

	@Autowired
	CatDevHCRemitInfoRepository catDevHCRemitInfoRepository;

	@Autowired
	CatDevRemitInfoRepository catDevRemitInfoRepository;

	@Autowired
	CacheService cacheService;

	@Autowired
	CatDevService catDevService;

	@Autowired
	AsyncService asyncService;

	@Autowired
	Dao<CatDevZJInviteInfoResp> zjdao;

	@Autowired
	Dao<CatDevZJInviteDetailedResp.InvitedPersonData> zjDetailedDao;
	
	@Autowired
	Dao<CatDevUserInfoResp.TLJInfo> tljInfoDao;
	
	@Autowired
	Dao<CatDevInviteTeamInfoResp> inviteTeamInfoRespDao;
	
	@Autowired
	Dao<CatDevHCInviteInfoResp> hcInviteInfoRespDao;

	@Autowired
	Dao<CatDevHCInviteIncomeHistory> catDevHCInviteIncomeHistoryDao;
	
	@Autowired
	Dao<CatDevTeamRebateResp> teamRebateRespDao;

	@Autowired
	CatDev5088InviteIncomeHistoryRepository catDev5088InviteIncomeHistoryRepository;

	@Autowired
	Dao<InviteHistory> idao;

	@Autowired
	Dao<InviteRemit> rdao;
	
	@Autowired
	private Dao<CatDevRebateInfoResp> rebateInfoRespDao;

	@Autowired
	Configs configs;

	@Autowired
	@Qualifier("redis15")
	RedisTemplate<String, Object> redis15;

	/* 邀请人邀请信息 */
	private final String CAT_INVITER_INFO = "CAT_INVITER_INFO";

	@Override
	public Map<String, String> getInviteUrl(int rtype, int utype,int ctype, String pid) {
		CatDevUserInfo userInfo = catDevService.getCatDevUserInfoByPid(pid);
		if (userInfo == null) {
			return null;
		}
		/**
		 * p1:pid p2:utype, p3:Icon, p4:name, p5:rtype
		 */
		String icon = userInfo.getIcon();

		String url = "https://mall.jiuqumao.cn/share/?p1=" + AesEncryptUtils.encryptBySalt(pid) + "&p2=" + utype
				+ "&p3=" + icon + "&p4=" + AesEncryptUtils.decrypt(userInfo.getNikename()) + "&p5=" + rtype+"&p6="+ctype;

		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + configs.getWxAppid()
				+ "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=1001#wechat_redirect";

		Map<String, String> data = new HashMap<>();
		data.put("name", AesEncryptUtils.decrypt(userInfo.getNikename()));
		data.put("url", path);
		return data;
	}

	private Map<String, String> getInviteUrl2(int rtype, int appId, int utype, String pid) {
		CatDevUserInfo userInfo = catDevService.getCatDevUserInfoByPid(pid);
		if (userInfo == null) {
			return null;
		}
		/**
		 * p1:pid p2:utype, p3:Icon, p4:name, p5:rtype
		 */
		String icon = userInfo.getIcon();

		String url1 = "https://mall.jiuqumao.cn/share/?p1=" + AesEncryptUtils.encryptBySalt(pid) + "&p2=" + utype
				+ "&p3=" + icon + "&p4=" + AesEncryptUtils.decrypt(userInfo.getNikename()) + "&p5=" + rtype;

		CatDevInviteUrlInfoResp urlInfoResp = new CatDevInviteUrlInfoResp(pid, utype, icon,
				AesEncryptUtils.decrypt(userInfo.getNikename()));
		// 获取最新版本链接
		CatAppVersionInfoResp appResp = cacheService.getLastAppVersion(rtype, appId, "official-001");
		urlInfoResp.setLink(appResp.getLinks());
		urlInfoResp.setUpdateDate(LocalDate.now().toString());
		// 生成邀请人key
		String string = pid + "_" + utype + rtype + appId;
		String key = Base64.encodeBase64URLSafeString(string.getBytes());

		// 判断是否已存在
		if (!redis15.opsForHash().hasKey(CAT_INVITER_INFO, key)) {
			redis15.opsForHash().put(CAT_INVITER_INFO, key, urlInfoResp);
		} else {
			// 判断查询出的是否与缓存中的数据相同
			CatDevInviteUrlInfoResp redisUrlInfoResp = (CatDevInviteUrlInfoResp) redis15.opsForHash()
					.get(CAT_INVITER_INFO, key);
			// 如果与缓存中数据不一样则更新缓存数据
			if (!redisUrlInfoResp.equals(urlInfoResp)) {
				redis15.opsForHash().put(CAT_INVITER_INFO, key, urlInfoResp);
			}
		}

		String url = "https://mall.jiuqumao.cn/share/?key=" + key;

		try {
			url = URLEncoder.encode(url, "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		String path = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + configs.getWxAppid()
				+ "&redirect_uri=" + url + "&response_type=code&scope=snsapi_userinfo&state=1001#wechat_redirect";

		Map<String, String> data = new HashMap<>();
		data.put("name", AesEncryptUtils.decrypt(userInfo.getNikename()));
		data.put("url", path);
		return data;
	}

	@Override
	public CatDevZJInviteInfoResp getZJInviteInfo(int rtype, String pid) {
		CatDevZJInviteInfoResp resp = zjdao.selectOne(new CatDevZJInviteInfoResp(pid), "getZJInviteInfo");
		if (resp.getIncome() < 0) {
			resp.setIncome(0);
		}
		return resp;
	}

	@Override
	public CatDevHCInviteInfoResp getHCInviteInfo(int rtype, String pid) {
		CatDevUserInfo dev = catDevService.getCatDevUserInfoByPid(pid);
		List<IncomeData> rlist = new ArrayList<IncomeData>();

		CatDevHCInviteInfoResp result = new CatDevHCInviteInfoResp(pid, 0, 0,
				LocalDateTime.now().plusDays(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS), rlist, 0);
		List<CatDevHCInviteIncomeHistory> inviteList = catDevHCInviteIncomeHistoryDao
				.list(new CatDevHCInviteIncomeHistory(pid), "getInviteIncomeHistory");
		/* 目前无邀请任务 */
		if (inviteList == null || inviteList.isEmpty()) {
			String stime = TJKUtils.DateTime();
			String ctime = stime, ltime = stime;
			String etime = TJKUtils.parse2LocalDateTime(stime).plusDays(1)
					.format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS);
			// 本轮首次进入,直接奖励2.8
			// 生成本轮活动ID
			String aid = "HC" + TJKUtils.DateTime("yyMMddhhmmss") + pid;
			CatDevHCInviteIncomeHistory inviteInfo = new CatDevHCInviteIncomeHistory(pid, stime, etime, 280, 0, "-", 1,
					0, ctime, ltime, "-", aid);
			catDevHCInviteIncomeHistoryRepository.saveAndFlush(inviteInfo);
			result.setIsfirst(1);
			inviteList = new ArrayList<>();
			inviteList.add(inviteInfo);
		}
		/* 计算总金额 */
		long yincome = 0;
		for (CatDevHCInviteIncomeHistory catDevHCInviteIncomeHistory : inviteList) {
			yincome += catDevHCInviteIncomeHistory.getIncome();
			IncomeData item = new IncomeData(catDevHCInviteIncomeHistory.getIncome());

			/* 邀请来源（0.个人中心分享、1.刮刮卡进入、2.神奇便利店进入、3.微信邀请成功） */
			if (catDevHCInviteIncomeHistory.getYtype() == 0) {
				item.setLicon(dev.getIcon().replace("http://", "https://"));
				item.setLname(AesEncryptUtils.decrypt(dev.getNikename()));
				item.setLtype(0);
			} else if (catDevHCInviteIncomeHistory.getYtype() == 1) {
				item.setLicon("https://img.jiuqumao.cn/imgs/invite/card.png");
				item.setLname("刮刮卡");
				item.setLtype(1);
			} else if (catDevHCInviteIncomeHistory.getYtype() == 2) {
				item.setLicon("https://img.jiuqumao.cn/imgs/invite/shop.png");
				item.setLname("神奇便利店");
				item.setLtype(2);
			} else if (catDevHCInviteIncomeHistory.getYtype() == 3) {
				CatDevUserInfo ydev = catDevService
						.getCatDevUserInfoByUnionid(catDevHCInviteIncomeHistory.getYunionid());
				if (ydev == null) {
					item.setLicon(dev.getIcon().replace("http://", "https://"));
					item.setLname(AesEncryptUtils.decrypt(dev.getNikename()));
				} else {
					item.setLicon(ydev.getIcon().replace("http://", "https://"));
					item.setLname(AesEncryptUtils.decrypt(ydev.getNikename()));
				}
				item.setLtype(3);
			}
			rlist.add(item);
		}
//		yincome = yincome >= 1000 ? 960 : yincome;
		result.setIncome(yincome);
		result.setLstatus(inviteList.get(0).getHstatus());
		result.setEtime(inviteList.get(0).getEtime());
		result.setRlist(rlist);
		return result;
	}

	@Override
	public CatDevHCInviteHistoryResp setHCInviteInfo(int rtype, int ltype, String pid) {
		boolean isOk = false;
		CatDevHCInviteHistoryResp result = new CatDevHCInviteHistoryResp();
		CatDevHCInviteIncomeHistory inviteInfo = null;
		String stime = TJKUtils.DateTime();
		String ctime = stime, ltime = stime;
		String etime = TJKUtils.parse2LocalDateTime(stime).plusDays(1).format(DateAPIUtils.FORMATTER_YYYYMMDDHHMMSS);
		List<CatDevHCInviteIncomeHistory> inviteList = catDevHCInviteIncomeHistoryRepository.getInviteInfos(pid);
		String aid = null;
		/* 非本轮活动第一次进入 */
		if (inviteList != null && inviteList.size() > 0) {
			stime = inviteList.get(0).getStime();
			etime = inviteList.get(0).getEtime();
			ctime = TJKUtils.DateTime();
			ltime = ctime;
			aid = inviteList.get(0).getAid();
		} else {
			inviteList = new ArrayList<>();
			// 生成活动ID
			aid = "HC" + TJKUtils.DateTime("yyMMddhhmmss") + pid;
		}

		result.setLtype(ltype);
		result.setEtime(etime);

//		/* 前两次进入奖励2.8元 */
//		if (inviteList.size() < 2) {
//			inviteInfo = new CatDevHCInviteIncomeHistory(pid, stime, etime, 280, ltype, "-", 1, 0, ctime, ltime, "-");
//			result.setIncome(280);
//		} else {
		/* 计算总金额 */
		long yincome = 0;

		/* 邀请成功人数 */
		long ycount = 0;

		/* 计算便利店来源次数，限制2次 */
		long bld = 0;

		/* 计算刮刮卡来源次数，限制2次 */
		long ggk = 0;

		/* 计算分享次数，限制2次 */
		long fx = 0;

		for (CatDevHCInviteIncomeHistory catDevHCInviteIncomeHistory : inviteList) {
			if (catDevHCInviteIncomeHistory.getYtype() == 0) {
				fx++;
			} else if (catDevHCInviteIncomeHistory.getYtype() == 1) {
				ggk++;
			} else if (catDevHCInviteIncomeHistory.getYtype() == 2) {
				bld++;
			} else if (catDevHCInviteIncomeHistory.getYtype() == 3) {
				ycount++;
			}
			yincome += catDevHCInviteIncomeHistory.getIncome();
		}
		/* 判断2人邀请奖励是否完成，完成修改状态并返回任务完成 */
		if (ycount == 2) {
			catDevHCInviteIncomeHistoryRepository.updInviteInfos(pid);
			isOk = true;
		} else {
			// 如果为微信分享则判断奖励次数,最大奖励2次
			if (ltype == 0 && fx < 2) {
				inviteInfo = new CatDevHCInviteIncomeHistory(pid, stime, etime, 280, ltype, "-", 1, 0, ctime, ltime,
						"-", aid);
				result.setIncome(280);
			} else {
				int incomeRandom = RandomUtils.nextInt(0, 3);
				long[] income = { 20, 60, 70 };
				long rincome = income[incomeRandom];

				/* 保证金额不大于960 */
				if (yincome + rincome >= 960) {
					rincome = rincome / 2;
				}
				if (ltype == 1 && ggk < 2) {
					inviteInfo = new CatDevHCInviteIncomeHistory(pid, stime, etime, rincome, ltype, "-", 1, 0, ctime,
							ltime, "-", aid);
				} else if (ltype == 2 && bld < 2) {
					inviteInfo = new CatDevHCInviteIncomeHistory(pid, stime, etime, rincome, ltype, "-", 1, 0, ctime,
							ltime, "-", aid);
				} else {
					inviteInfo = null;
				}
			}
		}
//		}
		/* 任务完成 */
		if (isOk) {
			result.setLstatus(1);
		} else if (inviteInfo == null) {
			result.setIncome(0);
		} else {
			if (catDevHCInviteIncomeHistoryRepository.saveAndFlush(inviteInfo) != null) {
				result = new CatDevHCInviteHistoryResp(ltype, inviteInfo.getIncome(), 0, inviteInfo.getLtime());
			} else {
				result.setIncome(0);
			}
		}
		return result;
	}

	@Override
	public Boolean openNewHCInviteInfo(Integer rtype, String pid) {
		List<CatDevHCInviteIncomeHistory> inviteList = catDevHCInviteIncomeHistoryDao
				.list(new CatDevHCInviteIncomeHistory(pid), "getInviteIncomeHistory");
		// 判断本轮活动是否已过期
		if (inviteList == null || inviteList.size() < 1) {
			return true;
		}
		if (inviteList.get(0).getHstatus() == 1
				|| TJKUtils.parse2LocalDateTime(inviteList.get(0).getEtime()).isBefore(LocalDateTime.now())) {
			String dateTime = TJKUtils.DateTime();
			inviteList.forEach(obj -> {
				obj.setHstatus(obj.getHstatus() == 1 ? 2 : 3);
				obj.setLtime(dateTime);
			});
			if (catDevHCInviteIncomeHistoryRepository.saveAll(inviteList) != null) {
				return true;
			}
		}
		return false;
	}

	@Override
	public Map<String, Object> setInviteInitInfo(int rtype, int ytype, String pid, String unionid) {
		// 查询此微信unionid是否已注册
		List<CatDevUserInfo> list = catDevUserInfoRepository.findByUnionid(unionid);
		Map<String, Object> resultMap = new HashMap<>();
		if (list != null && list.size() > 0) {
			resultMap.put("code", -11);
			resultMap.put("msg", "您已是九趣猫的用户,无法再领取奖励");
			return resultMap;
		}

		CatDevRelation dev = catDevRelationRepository.findByunionid(unionid);
		Map<Integer, String> map = new HashMap<>();
		if (dev != null) {
			/* 已被他人邀请成功 */
			final boolean isInviteed = dev.getYstatus() == 1;
			if (isInviteed) {
				map.put(-4061, "您已被他人邀请");
			}
			/* 还在7天邀请保护期内，无法被第三人邀请 */
			final boolean isUnLater = LocalDate.now().isAfter(TJKUtils.parse2LocalDate(dev.getStime()))
					&& LocalDate.now().isBefore(TJKUtils.parse2LocalDate(dev.getEtime()));
			if (!isUnLater) {
				map.put(-4061, "您已被他人邀请");
			}
		}
		pid = AesEncryptUtils.decryptBySalt(pid);
		CatDevRelation ydev = catDevRelationRepository.findByPid(pid);
		if (ydev != null) {
			dev = new CatDevRelation(unionid, "-", pid, ydev.getFpid(), ytype, 0, 0, LocalDate.now().toString(),
					LocalDate.now().plusDays(6).toString(), TJKUtils.DateTime(), TJKUtils.DateTime(), "5088点击邀请链接");
		} else {
			dev = new CatDevRelation(unionid, "-", pid, "1111111111", ytype, 0, 0, LocalDate.now().toString(),
					LocalDate.now().plusDays(6).toString(), TJKUtils.DateTime(), TJKUtils.DateTime(), "点击邀请链接");
		}
		if (catDevRelationRepository.saveAndFlush(dev) == null) {
			map.put(-10, "领取失败,请尝试重新进入领取");
		} else {
			map.put(1, "领取成功");
		}

		map.forEach((key, value) -> {
			resultMap.put("code", key);
			resultMap.put("msg", value);
		});
		return resultMap;
	}

	@Override
	public CatDevHCInviteInfoResp getHCInviteRimit(int rtype, String pid) {
		return hcInviteInfoRespDao.selectOne(new CatDevHCInviteInfoResp(pid), "getInviteNewUserRimit");
	}

	@Override
	public CatDevZJInviteDetailedResp getZJRewardDetailed(Integer rtype, String pid) {
		CatDevZJInviteDetailedResp result = new CatDevZJInviteDetailedResp(pid);
		CatDevZJInviteInfoResp infoResp = zjdao.selectOne(new CatDevZJInviteInfoResp(pid), "getZJInviteInfo");

		BeanUtils.copyProperties(infoResp, result);

		// 查询待领取的列表
		List<InvitedPersonData> unclaimedList = zjDetailedDao.list(new CatDevZJInviteInfoResp(pid, 0),
				"getInvitedPersonList");
		LocalDate nowDate = LocalDate.now();
		// 计算剩余天数
		unclaimedList.forEach(data -> {
			LocalDate endDate = TJKUtils.parse2LocalDate(data.getEndDate());
			Period period = Period.between(nowDate, endDate);
			data.setEffectiveDays(period.getDays() + 1);
			data.setNikename(AesEncryptUtils.decrypt(data.getNikename()));
			data.setIcon(data.getIcon().replace("http://", "https://"));
		});
		List<InvitedPersonData> receivedList = zjDetailedDao.list(new CatDevZJInviteInfoResp(pid, 1),
				"getInvitedPersonList");
		receivedList.forEach(data -> {
			data.setNikename(AesEncryptUtils.decrypt(data.getNikename()));
			data.setIcon(data.getIcon().replace("http://", "https://"));
		});

		result.setReceivedList(receivedList);
		result.setUnclaimedList(unclaimedList);
		return result;
	}

	@Override
	public Map<String, String> getOpenAppUrl(Integer rtype, Integer itype, String pid) {
		CatDevUserInfo userInfo = catDevService.getCatDevUserInfoByPid(pid);
		if (userInfo == null) {
			return null;
		}
		int pageId = 0;
		if (rtype == 1 || rtype == 2 || rtype == 3) {
			pageId = 0;
		} else {
			pageId = 1;
		}
		// pageId: 0.福利中心、1.15元或3元
		String url = "https://wx.jqmshare.cn/share/#/pages/remind/remind?pageId=" + pageId;
		Map<String, String> data = new HashMap<>();
		data.put("name", AesEncryptUtils.decrypt(userInfo.getNikename()));
		data.put("url", url);
		return data;
	}

	@Override
	public CatDevRemitRecordResp remitHC(int rtype, String pid, int qtype, String zaccount, String zrealname) {
		String nowTimeString = TJKUtils.DateTime();
		CatDevHCRemitInfo entity = new CatDevHCRemitInfo(pid, TJKUtils.DateTime(TJKUtils.YYYY_MM_DD), qtype, zaccount,
				zrealname, 10 * 100, nowTimeString, "-");
		entity.setLtime(nowTimeString);
		// 获取用户微信信息
		CatDevUserInfo catDevUserInfo = catDevService.getCatDevUserInfoByPid(pid);
		entity.setUnionid(catDevUserInfo.getUnionid());
		entity.setOpenid(catDevUserInfo.getOpenid());
		// 清除Redis中的记录
		asyncService.updateCatDevInviteAwardRecord(pid, 0, 0, "", 0);
		// 判断是否已完成新人任务
		List<CatDevHCInviteInfoResp> list = hcInviteInfoRespDao.list(new CatDevHCInviteInfoResp(pid),
				"getHCInviteNewUserInfo");
		// 遍历查询是否都已完成新人任务
		boolean isComplete = true;
		for (CatDevHCInviteInfoResp resp : list) {
			if (cacheService.getCatDevBeansByGame(resp.getPid()) < DrawProportionUtil.NEW_USER_TASK_BAENS_NUM) {
				isComplete = false;
				break;
			}
		}
		entity.setAid(list.get(0).getAid());
		CatDevHCRemitInfo remit = catDevHCRemitInfoRepository.saveAndFlush(entity);
		if (remit == null) {
			return null;
		}
		// 如果完成则直接进行打款操作
		if (isComplete) {
			CatDevRemitRecordResp remitRecordResp = catDevService.remit(rtype,1, pid, qtype, 2, zaccount, zrealname,
					10 * 100);
			remit.setOid(remitRecordResp.getOid());
			catDevHCRemitInfoRepository.saveAndFlush(remit);
		}
		CatDevRemitRecordResp recordResp = new CatDevRemitRecordResp();
		BeanUtils.copyProperties(remit, recordResp);
		return recordResp;
	}

	@Override
	public CatDevInviteUrlInfoResp getUrlInviterInfo(Integer rtype, Integer appId, String key) {
		CatDevInviteUrlInfoResp redisUrlInfoResp = (CatDevInviteUrlInfoResp) redis15.opsForHash().get(CAT_INVITER_INFO,
				key);
		if (redisUrlInfoResp != null) {
			CatDevUserInfo userInfo = catDevService.getCatDevUserInfoByPid(redisUrlInfoResp.getPid());
			// 是否更新Redis
			boolean isUpdateRedis = false;
			if (!userInfo.getIcon().equals(redisUrlInfoResp.getIcon())) {
				redisUrlInfoResp.setIcon(userInfo.getIcon());
				isUpdateRedis = true;
			}
			if (!redisUrlInfoResp.getUpdateDate().equals(LocalDate.now().toString())) {
				redisUrlInfoResp.setUpdateDate(LocalDate.now().toString());
				isUpdateRedis = true;
			}
			if (!redisUrlInfoResp.getNikename().equals(AesEncryptUtils.decrypt(userInfo.getNikename()))) {
				redisUrlInfoResp.setNikename(AesEncryptUtils.decrypt(userInfo.getNikename()));
				isUpdateRedis = true;
			}
			// 获取最新版本链接
			CatAppVersionInfoResp appResp = cacheService.getLastAppVersion(rtype, appId, "official-001");
			if (!redisUrlInfoResp.getLink().equals(appResp.getLinks())) {
				redisUrlInfoResp.setNikename(AesEncryptUtils.decrypt(userInfo.getNikename()));
				isUpdateRedis = true;
			}
			// 如果最后更新时间不为今天则进行更新
			if (isUpdateRedis) {
				redisUrlInfoResp.setUpdateDate(LocalDate.now().toString());
				redis15.opsForHash().put(CAT_INVITER_INFO, key, redisUrlInfoResp);
			}
		}
		return redisUrlInfoResp;
	}

	@Override
	public CatDev5088InviteInfoResp get5088InviteInfo(Integer rtype, String pid) {
		CatDev5088InviteInfoResp result = null;
		long income = 0, ycount = 0;
		List<CatDev5088InviteIncomeHistory> incomeList = catDev5088InviteIncomeHistoryRepository
				.findByYidAndIstatus(pid, 2);
		if (incomeList != null && !incomeList.isEmpty()) {
			ycount = incomeList.size();
			income = incomeList.stream().mapToLong(mapper -> {
				return mapper.getIncome();
			}).sum();
		}
		List<InviteHistory> history = idao.list(new CatDev5088InviteInfoResp(pid));
		List<InviteRemit> remitInfo = cacheService.getCatDev5088InviteRemitinfo();
		InviteRemit userRemitInfo = rdao.selectOne(new CatDev5088InviteInfoResp(pid), "userRemitInfo");
		if (userRemitInfo != null &&  remitInfo!=null) {
			for (InviteRemit inviteRemit : remitInfo) {
				if (inviteRemit.getIncome() == userRemitInfo.getIncome()) {
					int lcount = inviteRemit.getLcount() - userRemitInfo.getLcount();
					if (lcount < 0) {
						lcount = 0;
					}
					inviteRemit.setLcount(lcount);
					break;
				}
			}
		}
		if (history == null) {
			history = new ArrayList<InviteHistory>();
		}else {
			history=history.stream().map(mapper->{
				mapper.setYname(AesEncryptUtils.decrypt(mapper.getYname()));
				return mapper;
			}).collect(Collectors.toList());
		}
		result = new CatDev5088InviteInfoResp(ycount, income, history, remitInfo);
		return result;
	}

	@Override
	public Boolean set5088Inviteremit(String pid, long rcode, long rtype) {
		 
		return null;
	}

	@Override
	public CatDevInviteTeamInfoResp getMyTeamInfo(Integer rtype, String pid) {
		CatDevInviteTeamInfoResp infoResp = inviteTeamInfoRespDao.selectOne(new CatDev5088InviteInfoResp(pid), "getInviteTeamInfo");
		CatDevRebateInfoResp rebateInfoResp = rebateInfoRespDao.selectOne(new CatDevOrderResp(pid), "getOrderRebateInfoForInvite");
		CatDevRelation devRelation = cacheService.getInviteRelationByPid(pid);
		infoResp.setRebateInfo(rebateInfoResp);
		String name="";
		if (devRelation!=null && !devRelation.getFpid().equals("1111111111")) {
			name=cacheService.getCatDevUserInfoByPid(devRelation.getFpid());
		}
		infoResp.setInviteName(name);
		return infoResp;
	}

	@Override
	public ResultPage<CatDevTeamRebateResp> teamList(String pid, Pages pages) {
		ResultPage<CatDevTeamRebateResp> resp = teamRebateRespDao.listAndPages(new CatDev5088InviteInfoResp(pid), "getTeamRebateDataList", pages);
		if (resp!=null && resp.getTotal()>0 && resp.getList()!=null) {
			resp.getList().forEach(info->{
				info.setNikename(AesEncryptUtils.decrypt(info.getNikename()));
			});
		}
		return resp;
	}

	/**
	 * 获取淘礼金奖励明细
	 */
	@Override
	public List<TLJInfo> getZJTljDetailed(Integer rtype, String pid) {
		// TODO Auto-generated method stub
		//创建一个新的淘礼金信息表(这里的奖励是淘礼金，不是奖励金)
		ArrayList<TLJInfo> result=new ArrayList<CatDevUserInfoResp.TLJInfo>();
		//用户邀请好友返回的信息
		CatDevZJInviteInfoResp infoResp = zjdao.selectOne(new CatDevZJInviteInfoResp(pid), "getZJInviteInfo");
       //赋值
		BeanUtils.copyProperties(infoResp, result);
		//判断邀请好友是新用户还是老用户
		CatDevUserInfo resp=catDevUserInfoRepository.findByPid(pid);
		//1.如果邀请好友为新用户(淘礼金30+期限72h)
		if(resp.getUtype()==0) {
			if(!result.isEmpty() && result!=null) {
				//创建一个新的淘礼金信息表
				TLJInfo tInfo=new TLJInfo();
				tInfo.setLtlj(30);
				tInfo.setLtime(252000);	
			}else {
				return null;
			}
		}
		//2.反之为老用户(获取一次淘礼金补贴资格)	
		else {
			return null;
		}
		return result;	
	}
}
